package y2016.test;

import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParseTxt {

    /**
     * 正则表达式。
     * 一对括号一组，共分四组
     * 说明如下：
     * <p>  (^\n|\r|\r\n) 章节之前是换行符。换行符匹配，一般章节名都是换行的，第一章很可能不换，其余章节除非格式问题都会换行
     * <p>  (.*第)  匹配任意长度字符。需要考虑一些特殊的章节名如：002章，前面没有“第”字(难以实现匹配。。。),或者空白，或者形如：“正文 第XX章 xxx”，“第二卷 xx 第xx回 xxx”
     * <p>  ([零一二三四五六七八九十百千0123456789]{1,7}) 章节序号，可以是[零一二三四五六七八九十百千0123456789]中的任意一个字符组成的，长度为1~7个的字符串
     * <p>  [章节卷集部册篇回] 匹配其中任意个字符
     * <p>  (.*) 章节名称匹配
     * <p>  (\n|\r|\r\n) 章节结束后换行匹配
     **/
    private static String[] regexs = {
            "(^\n|\r|\r\n)(.{0,20})([零一二三四五六七八九十百千0123456789]{1,7})([章节回])(.*)(\n|\r|\r\n)",
            "(.*第)([零一二三四五六七八九十百千0123456789]{1,7})([章节篇回])(.*)",
            "(\n|\r|\r\n)(.*第)[零一二三四五六七八九十百千]{1,7}[章节卷集部册篇回][:：]?.*"

    };

    /**
     * 换行符匹配
     */
    private static String regexNewLine = "(\r\n|\r|\n|\n\r)";

    private static ArrayList<String> chapterNames;
    private static ArrayList<Integer> everyChapterStartIndexs;

    private static ArrayList<Integer> everyChapterEndIndexs;

    /**
     * 章节名称
     */
    public static ArrayList<String> getChapters() {
        return chapterNames;
    }

    /**
     * 每个章节结束的下标
     */
    public static ArrayList<Integer> getEveryChapterEndIndexs() {
        return everyChapterEndIndexs;
    }

    /**
     * 每个章节起始下标
     */
    public static ArrayList<Integer> getEveryChapterStartIndexs() {
        return everyChapterStartIndexs;
    }

    /**
     * 读书方法。将文字读到字符串sb参数中
     *
     * @param sb       装载txt所有文字的StringBuilder，需要先实例化
     * @param file     TXT文件的File对象。作为当sb为空时，进行读取的依据
     * @param indexAll 所有的分页第一个字的下标集合，需要先实例化。当分页线程循分页时，将不停的增加其大小，只要其中存在下标，就可以依此，绘制文字。
     */
    public static void readBookToSB(StringBuilder sb, File file) {
        if (!file.exists()) {
            return;
        }
        if (sb == null) {//防空。。。
            sb = new StringBuilder();
        }
        JudgeFile judgeFile = new JudgeFile();
        String charseName = judgeFile.getEncoding(file);
        FileInputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = new FileInputStream(file);
            isr = new InputStreamReader(is, charseName);
            br = new BufferedReader(isr);
            char[] chs = new char[1024 * 25];
            int len = 0;
            while ((len = br.read(chs)) != -1) {
                sb.append(new String(chs, 0, len));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    //	public static boolean parserChapterName(String chapter){
    //
    //		String regex = "[零一二三四五六七八九十百千0123456789]*[章节回]";
    //		String[] strs = chapter.split(regex);
    //			if ((strs[0].endsWith("第")) || (strs[0].length()==0)||(strs[0].endsWith(" "))) {
    //				return true;
    //			}
    //			System.out.println(strs[0]);
    //		return false;
    //	}

    static int i = 0;
    /**
     * 第一组带有全角符号。匹配除了[]中的字符串
     * 第二组，任意长度字符
     */
    private static String[] regexGroup2 = {
            "(^[\\s 　]*)([^-－―：：,，.。;；*]*)([\\s 　]*)(.*)",
    };

    /**
     * 取出带-－―：：形式的字符串。用来排除例如日期、时间等格式，如：
     * <p>2016-00-02
     * <p>16:25
     * <p>数量：16
     * <p>http://www.hao123
     *
     * @param group2
     * @return 当含有[-－―：：,，.。;；*]时，返回false。否则true
     */
    public static boolean matcherGroup2(String group2) {
        Pattern pattern = Pattern.compile(regexGroup2[0]);
        Matcher matcher = pattern.matcher(group2);
        matcher.find();

        String newGroup1 = matcher.group(1);
        String newGroup2 = matcher.group(2);
        String newGroup3 = matcher.group(3);
        String newGroup4 = matcher.group(4);

//	System.out.println(newGroup1);
//	System.out.println(newGroup2);
//	System.out.println(newGroup3);
//	System.out.println(newGroup4);
//	System.out.println(newGroup5);

        if (newGroup1.length() > 0) {//当第一组是空格时
            if (newGroup2.length() == 0) {//如果第二组不存在数字（从参数传来的一定会有的）
//			System.out.println(group2);
                return true;
            } else {//如果第二组存在数字
                if (newGroup3.length() > 0) {//并且第三组存在空格
                    return true;
                }

            }
        } else if (newGroup1.length() == 0) {//如果第一组没有空格
            if (newGroup2.length() > 0) {//如果第二组存在数字
                if (newGroup3.length() == 0) {
                    if (newGroup4.length() > 0) {
                        return false;
                    }
                    return true;
                }
            }
        }
        return false;

//	if ( (newGroup2.endsWith(" ")) || (newGroup2.endsWith("　")) || (newGroup2.length()==0) ) {
//		return true;
//	}
//	else {
//		return false;
//	}

//		return true;
    }


    /**
     * 最多匹配到九千九百九十九（7个汉字）章，9999999（7个数字：9百99万9千9百99）章
     */
    private static String regex = "(^\n|\r|\r\n)(.{0,30})([零一二三四五六七八九十百千0123456789０１２３４５６７８９]{1,7})([章节回]{0,1})([\\s|　]{0,1}.*)(\n|\r|\r\n)";
    private static int oldMathcherEnd;

    @SuppressWarnings("unchecked")
    public static void parserChapter(StringBuilder sb) {
        if (everyChapterStartIndexs == null) {
            everyChapterStartIndexs = new ArrayList<Integer>();
        }
        if (everyChapterStartIndexs.size() > 0) {
            everyChapterStartIndexs.clear();
        }

        everyChapterStartIndexs.add(0);


        if (chapterNames == null) {
            chapterNames = new ArrayList<String>();
        }
        if (chapterNames.size() > 0) {
            chapterNames.clear();
        }

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sb);
        while (matcher.find()) {

            String newGroup0 = matcher.group(0);
            String newGroup2 = matcher.group(2);
            String trueChapterName = newGroup0.replaceAll(regexNewLine, "");

            int newMathcherStart = matcher.start();
//			System.out.println(trueChapterName);

            if (newMathcherStart - oldMathcherEnd > 8) {//可以去除靠的很近的重复的章节名

                if (matcher.group(4).length() > 0) {//包含章节回
//				boolean groupFlag = matcherChapter(trueChapterName);
                    System.out.println(trueChapterName);
                } else {//不包含章节回时需要判断是否加入
                    boolean groupFlag = matcherGroup2(matcher.group(2));
                    if (groupFlag) {
//					System.out.println(trueChapterName);
                        chapterNames.add(trueChapterName);
                        everyChapterStartIndexs.add(newMathcherStart);
                    }
                }

            }
            oldMathcherEnd = matcher.end();
        }
        everyChapterEndIndexs = (ArrayList<Integer>) everyChapterStartIndexs.clone();
        everyChapterEndIndexs.remove(0);
        everyChapterEndIndexs.add(sb.length() - 1);
        //		Log.d("章节起始下标：", everyChapterStartIndexs+" ");
        //		Log.d("章节结束下标：", everyChapterEndIndexs+" ");
        System.out.println("章节起始下标：" + everyChapterStartIndexs + " ");
        System.out.println("章节结束下标：" + everyChapterEndIndexs + " ");
    }

    private static String[] regexChapter = {
            "(^\n|\r|\r\n)(.{0,25}[零一二三四五六七八九十百千0123456789０１２３４５６７８９]{1,7}.{0,25})(\n|\r|\r\n)",
            "([零一二三四五六七八九十百千0123456789０１２３４５６７８９]{1,7})([章节回])([\\s　]*)(.*)"

    };

    public static void matcherChapter(StringBuilder text) {
        Pattern pattern = Pattern.compile(regexChapter[0]);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String newGroup2 = matcher.group(2);
            regexGroup2(newGroup2);

        }

    }

    private static void regexGroup2(String group2) {
        Pattern pattern = Pattern.compile(regexChapter[1]);
        Matcher matcher = pattern.matcher(group2);


        if (group2.contains("章") || group2.contains("节") || group2.contains("回")) {
//			System.out.println(group2);
            while (matcher.find()) {
                String newGroup0 = matcher.group(0);
                String newGroup1 = matcher.group(1);
                String newGroup2 = matcher.group(2);
                String newGroup3 = matcher.group(3);
                String newGroup4 = matcher.group(4);
//				System.out.println(newGroup0);
//				System.out.println(newGroup1);
//				System.out.println(newGroup2);
//				System.out.println(newGroup3);
//				System.out.println(newGroup4);
//				System.out.println(group2);
                if (newGroup4.length() == 0) {
                    System.out.println(group2);
                }
            }
        }

    }

}

